package com.presto.directo.utils

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import androidx.core.app.ActivityCompat
import com.presto.directo.entity.SmsEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object SmsListUtil {

    suspend fun getSms(context: Context): List<SmsEntity> {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
            return arrayListOf()
        }
        return withContext(Dispatchers.IO) {
            val list = arrayListOf<SmsEntity>()
            val uri = Uri.parse("content://sms/")
            val projection = arrayOf("_id", "address", "body", "date", "type", "read", "status")
            var cursor: Cursor? = null
            try {
                cursor = context.contentResolver.query(uri, projection, null, null, null)!!
                while (cursor.moveToNext()) {
                    val number = cursor.getString(cursor.getColumnIndex("address")) ?: ""
                    val body = cursor.getString(cursor.getColumnIndex("body")) ?: ""
                    val date = cursor.getString(cursor.getColumnIndex("date")) ?: ""
                    val type = cursor.getString(cursor.getColumnIndex("type")) ?: ""
                    val read = cursor.getString(cursor.getColumnIndex("read")) ?: ""
                    val status = cursor.getString(cursor.getColumnIndex("status")) ?: ""
                    val smsEntity = SmsEntity(number, body, date, type, read, status)
                    list.add(smsEntity)
                }
                list
            } catch (e: Exception) {
                list
            } finally {
                cursor?.close()
            }
        }

    }

}